# -*- mode: makefile-gmake -*-
#
#  Copyright (c) 2007 by Duzy Chan <duzy@duzy.ws>
#

ifeq ($(origin YISC_DIR),undefined)
     $(error variable YISC_DIR unspecified!)
endif
#-include $(YISC_DIR)/global.mak
include $(YISC_DIR)/global.mak

ifeq ($(PLATFORM),linux)
    LIBS += -lboost_thread-gcc41-mt
    CXXFLAGS += -W -Wall -g -DHTTP_SERVER_LOGGING=true
else
    LIBS += -lws2_32 -lmswsock -lboost_thread-mgw34-mt-1_34
    CXXFLAGS += -W -Wall -g -D_WIN32_WINNT=0x0500 -DHTTP_SERVER_LOGGING=true
endif

UNIT_TEST_OBJS = $(filter-out main.o,$(OBJECTS))
UNIT_TEST_ITEM = $(wildcard *.t)
UNIT_TESTS = $(UNIT_TEST_ITEM:.t=.test)

PHONY += all
all: $(DEPLOYMENT)

TARGET = libyisc-http-server.a
DEPLOYMENT = $(LIB)/$(TARGET)
$(DEPLOYMENT):$(TARGET)
	@if [ ! -d $(LIB) ] ; then \
		mkdir -pv $(LIB) ; \
	fi ;
	$(MV) $< $@

$(TARGET): $(OBJECTS)
	@echo Building...
	@echo -n "  "
	$(AR) $@ $^

# %.exe: %.o
# 	@echo Building...
# 	@echo -n "  "
# 	$(LINK) -o $@ $^ $(LIBS)

%.o: %.cpp $(INCLUDE)/http/server/%.hpp
	@echo Compiling...
	@echo -n "  "
	$(COMPILE) -o $@ $^

PHONY += clean
clean:
	@echo Cleaning "$(OBJECTS) $(TARGET)" ...
	@$(REMOVE) $(TARGET) 
	@$(REMOVE) $(OBJECTS)
	@echo " Doned."

PHONY += tidy
tidy: clean
	@$(REMOVE) $(UNIT_TESTS) *.exe *.o *~
	@$(REMOVE) $(patsubst %.t,%.t.cc,$(UNIT_TEST_ITEM))

PHONY += test
test: all
	./$(TARGET) 127.0.0.1 80

PHONY += unit-test
unit-test: $(UNIT_TESTS)
	@echo ; echo "========== Running unit tests ==" ; \
	PASSED=0 ; FAILED=0 ; ID=0 ; \
	for T in $(UNIT_TESTS) ; \
	do \
		ID=`expr $$ID + 1` ; \
		echo "test:$$ID: $$T " ; \
		if ./$$T ; then \
			PASSED=`expr $$PASSED + 1` ; \
			echo "    PASSED" ; \
		else \
			FAILED=`expr $$FAILED + 1` ; \
			echo "    FAILED" ; \
		fi \
	done ; \
	echo "========== PASSED($$PASSED), FAILED($$FAILED) ==" ; \
	echo

define build_test
	@echo -n "Build unit test($1)..." ; \
	if $(LINK) -o $1 $2 $(LIBS) ; then \
		echo "Done." ; \
	else \
		echo "Failed." ; \
	fi ; \
	echo #$(REMOVE) $(1:.test=.cc)
endef

define compile_test
	@echo -n "Compiling unit test($1)..." ; \
	if $(COMPILE) -x c++ -I. -o $1 $2 ; then \
		echo "Done." ; \
	else \
		echo "Failed" ; \
	fi ;
endef

%.test: %.t.o $(UNIT_TEST_OBJS)
	$(call build_test,$@,$^)

%.t.o: %.t
	$(call compile_test,$@,$<)

.PHONY: $(PHONY)
